<template>
  <div class="category-container">
    <div class="page-header">
      <h2>商品分类管理</h2>
      <el-button type="primary" @click="showAddDialog">添加分类</el-button>
    </div>
    
    <el-table
      :data="categories"
      style="width: 100%"
      row-key="id"
      border
      v-loading="loading"
      default-expand-all
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column
        prop="id"
        label="ID"
        width="80">
      </el-table-column>
      <el-table-column
        prop="name"
        label="分类名称">
      </el-table-column>
      <el-table-column
        prop="icon"
        label="图标"
        width="120">
        <template slot-scope="scope">
          <i :class="scope.row.icon"></i>
        </template>
      </el-table-column>
      <el-table-column
        prop="sortOrder"
        label="排序"
        width="80">
      </el-table-column>
      <el-table-column
        label="状态"
        width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="changeStatus(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
            size="mini"
            type="primary"
            @click="handleAddSub(scope.row)">添加子分类</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 添加/编辑分类对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="40%">
      <el-form :model="categoryForm" label-width="100px" :rules="rules" ref="categoryForm">
        <el-form-item label="父级分类" v-if="isAddSub">
          <el-input v-model="parentCategoryName" disabled></el-input>
        </el-form-item>
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryForm.name" placeholder="请输入分类名称"></el-input>
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-input v-model="categoryForm.icon" placeholder="请输入图标类名">
            <template slot="append">
              <i :class="categoryForm.icon || 'el-icon-goods'"></i>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="categoryForm.sortOrder" :min="0" :max="1000"></el-input-number>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="categoryForm.status"
            active-text="启用"
            inactive-text="禁用">
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getCategoryTree, addCategory, updateCategory, deleteCategory, updateCategoryStatus } from '@/api/category';

export default {
  name: 'CategoryManagement',
  data() {
    return {
      loading: false,
      categories: [],
      dialogVisible: false,
      dialogTitle: '添加分类',
      categoryForm: {
        name: '',
        icon: 'el-icon-food',
        sortOrder: 0,
        status: true
      },
      rules: {
        name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ]
      },
      isAddSub: false,
      parentCategory: null,
      parentCategoryName: '',
      isEdit: false,
      currentCategory: null
    }
  },
  created() {
    this.fetchCategories();
  },
  methods: {
    // 获取分类列表
    fetchCategories() {
      this.loading = true;
      getCategoryTree()
        .then(res => {
          this.categories = res.data || [];
        })
        .catch(err => {
          console.error('获取分类失败', err);
          this.$message.error('获取分类列表失败');
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    showAddDialog() {
      this.isAddSub = false;
      this.isEdit = false;
      this.dialogTitle = '添加分类';
      this.categoryForm = {
        name: '',
        icon: 'el-icon-food',
        sortOrder: 0,
        status: true
      };
      this.dialogVisible = true;
    },
    
    handleEdit(row) {
      this.isEdit = true;
      this.isAddSub = false;
      this.dialogTitle = '编辑分类';
      this.currentCategory = row;
      this.categoryForm = {
        id: row.id,
        name: row.name,
        icon: row.icon,
        sortOrder: row.sortOrder,
        status: row.status
      };
      this.dialogVisible = true;
    },
    
    handleAddSub(row) {
      this.isAddSub = true;
      this.isEdit = false;
      this.dialogTitle = '添加子分类';
      this.parentCategory = row;
      this.parentCategoryName = row.name;
      this.categoryForm = {
        parentId: row.id,
        name: '',
        icon: 'el-icon-food',
        sortOrder: 0,
        status: true
      };
      this.dialogVisible = true;
    },
    
    handleDelete(row) {
      this.$confirm('确认删除该分类吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true;
        deleteCategory(row.id)
          .then(() => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.fetchCategories(); // 重新加载数据
          })
          .catch(err => {
            console.error('删除分类失败', err);
            this.$message.error('删除分类失败');
          })
          .finally(() => {
            this.loading = false;
          });
      }).catch(() => {
        // 取消删除操作
      });
    },
    
    // 修改分类状态
    changeStatus(row) {
      this.loading = true;
      updateCategoryStatus(row.id, row.status)
        .then(() => {
          this.$message({
            type: 'success',
            message: `状态修改成功`
          });
        })
        .catch(err => {
          console.error('修改状态失败', err);
          this.$message.error('修改状态失败');
          // 回滚状态
          row.status = !row.status;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    submitForm() {
      this.$refs.categoryForm.validate(valid => {
        if (valid) {
          this.loading = true;
          
          // 根据不同情况调用不同接口
          const apiMethod = this.isEdit ? updateCategory : addCategory;
          const successMsg = this.isEdit ? '编辑成功' : (this.isAddSub ? '添加子分类成功' : '添加分类成功');
          
          apiMethod(this.categoryForm)
            .then(() => {
              this.$message({
                type: 'success',
                message: successMsg
              });
              this.dialogVisible = false;
              this.fetchCategories(); // 重新加载数据
            })
            .catch(err => {
              console.error('操作失败', err);
              this.$message.error('操作失败');
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },
    
    // 帮助方法 - 已不再需要，通过重新获取数据替代
    removeCategoryById(id) {
      // 递归查找并删除分类
      const removeFromArray = (arr) => {
        const index = arr.findIndex(item => item.id === id);
        if (index > -1) {
          arr.splice(index, 1);
          return true;
        }
        
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].children && arr[i].children.length > 0) {
            if (removeFromArray(arr[i].children)) {
              return true;
            }
          }
        }
        
        return false;
      };
      
      removeFromArray(this.categories);
    }
  }
}
</script>

<style scoped>
.category-container {
  padding: 20px;
}
.page-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style> 